package org.subatu.orm.util;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 反射工具类
 */
public class ClassUtil {

    /**
     * 给 属性设置值
     *
     * @param entity
     * @param field
     * @param value
     */
    public static void setFieldValue(Object entity, Field field, Object value) {
        if (value == null) {
            return;
        }
        boolean acc = field.isAccessible();
        field.setAccessible(true);
        try {
            field.set(entity, value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            field.setAccessible(acc);
        }
    }

    /**
     * 读取属性的值
     *
     * @param entity
     * @param field
     * @return
     */
    public static Object getFieldValue(Object entity, Field field) {
        boolean acc = field.isAccessible();
        field.setAccessible(true);
        try {
            return field.get(entity);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            field.setAccessible(acc);
        }
    }

    public static List getAllValues(Object entity, List<Field> allFieldList) {
        List values = new ArrayList();
        for (Field field : allFieldList) {
            values.add(ClassUtil.getFieldValue(entity, field));
        }
        return values;
    }

    // 根据字段名获取字段
    public static Field getField(Class<?> clazz, String fieldName) {
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            if (field.getName().equals(fieldName)) {
                return field;
            }
        }

        return null;
    }

    // 获取泛型的具体类型
    public static Class<?> getTClazz(Class serviceClazz) {
        ParameterizedType types = (ParameterizedType) serviceClazz.getGenericSuperclass();
        for (Type type : types.getActualTypeArguments()) {
            System.out.println(type);
            if (type instanceof Class) {
                return (Class<?>) type;
            } else if (type instanceof ParameterizedType) {
                ParameterizedType paramType = (ParameterizedType) type;
                Type[] actualTypeArguments = paramType.getActualTypeArguments();
                if (actualTypeArguments.length > 0) {
                    System.out.println("这里需要完善方法...." + actualTypeArguments[0]);
                    // return getGenericTypeName(actualTypeArguments[0]); // 递归调用来处理泛型参数
                }
            }
        }
        return null;
    }
}
